<template>
    <GhNavBar title="登录" rightText="注册" @click-right="clickRight" />
    <div class="login-page" >
            <!-- 头部 -->
           <div class="login-head">
            <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
            <a href="javascript:;">
              <span @click="isPass = !isPass">
                {{ isPass ? '短信验证码登录' : '密码登录' }}
              </span>
              <van-icon name="arrow"></van-icon>
            </a>
            </div>
        <!-- 表单 -->
              <van-form autocomplete="off" @submit="onSubmit" ref="form" >
                <van-field
                    name="mobile"
                    v-model="account"
                    :rules="userFormRules.account"
                    placeholder="请输入手机号"
                    type="tel">
                </van-field>
                <van-field
                  v-if="isPass"
                  v-model="password"
                  :rules="userFormRules.password"
                  placeholder="请输入密码"
                  :type="isShow ? 'text' : 'password'"
                >
                      <template #button>
                           <gh-icon
                             :name="`login-eye-${isShow ? 'on' : 'off'}`"
                             @click="isShow = !isShow"
                             style="margin-right: 10px"
                           ></gh-icon>
                      </template>
                </van-field>
                <van-field v-else
                  placeholder="短信验证码"
                  :rules="userFormRules.code"
                  v-model="code"
                >
                  <template #button>
                    <span class="btn-send"  :class="{ active: time > 0 }" @click="onSend" > 
                      {{ time > 0 ? `${time}s后再次发送` :'发送验证码' }}
                    </span>
                  </template>
                </van-field>
                <div class="gh-cell">
                       <van-checkbox v-model="agree">
                         <span>我已同意</span>
                         <a href="javascript:;">用户协议</a>
                         <span>及</span>
                         <a href="javascript:;">隐私条款</a>
                       </van-checkbox>
                  </div>
                <div class="gh-cell">
                  <!-- 兜底 校验 native-type -->
                  <van-button native-type="submit" :loading="isRegistering" :disabled="isRegistering" block round type="primary">
                    登 录
                  </van-button>
                </div>
                <div class="gh-cell">
                  <a href="javascript:;">忘记密码？</a>
                </div>
            </van-form>
         <!-- 底部 -->
             <div class="login-other">
               <van-divider>第三方登录</van-divider>
               <a
                 class="icon"
               >
                 <img src="@/assets/qq.svg" alt="" />
               </a>
             </div>


</div>

</template>

<script setup>
import { loginByCode, loginByPassword,getIdentCode } from '@/services/user'
import GhNavBar from '../components/gh-nav-bar.vue'
import GhIcon from '../components/gh-icon.vue'
import {ref,computed,onMounted,onUnmounted} from 'vue'
import {useUserStore} from '@/stores'
import {useRouter,useRoute} from 'vue-router'
import { Toast, Dialog } from 'vant';
import axios from 'axios'
import 'vant/es/toast/style'
const store = useUserStore()
//跳转路由使用
const router=useRouter();
// 获取路由参数
const route = useRoute()


// 输入框的双向绑定
const account = ref('13643042484')
const password = ref('wyl123456789!')
const code = ref('')
// 短信登录界面切换
const isPass = ref(true)
// 密码的可见与不可见
const isShow = ref(false)
 //是否同意网站使用协议
 const agree =ref(false)
//前端校验规则
 const accountRule =ref([{
          required: true,
          message: '手机号不能为空'
        }, {
          pattern: /^1[3|5|7|8]\d{9}$/,
          message: '手机号格式错误'
        }],)
const codeRule =ref([{
          required: true,
          message: '验证码不能为空'
        }, {
          pattern: /^\d{6}$/,
          message: '验证码格式错误'
        }])
const passwordRule=ref([{
    required:true,
    message:'密码不能为空'
},
{
    pattern:/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
    message:'密码格式错误'
}])
// 将验证规则对象暴露给模板
const userFormRules = computed(() => {
  return {
    account: accountRule.value,
    code: codeRule.value,
    password:passwordRule.value
  };
});
//定义验证码发送倒计时间
const time=ref(0);
let timer;
//定义发送验证码的函数
const onSend =async()=>{
       if(!account.value){
           Toast('请先输入手机号！')
           return
       }
       
       if(time.value>0)return;
      const res=await getIdentCode(account.value).then((response)=>{
        return response
    }).catch((error)=>{
     return error
    })
       console.log(res.data)
       Toast('发送成功')
       time.value = 60
       // 开启倒计时
       if (timer) clearInterval(timer)
        timer = window.setInterval(() => {
             time.value--
             if (time.value <= 0) {clearInterval(timer)}
           }, 1000)
}

const isRegistering = ref(false);


//定义登录的函数
const onSubmit=async()=>{
if (!agree.value) return Toast('请先勾选协议')
 // 进行登录(合并短信登录)
//  const res = isPass.value
//     ? await loginByPassword(account.value, password.value)
//     : await loginByCode(account.value, code.value)
isRegistering.value = true;
//从localstorage中获取token
// const token= localStorage.getItem('tokenStr')

setTimeout(async() => {

    // let res;
 const res = isPass.value
    ? await loginByPassword(account.value, password.value).then((response)=>{
      return response
    }).catch((error)=>{
     return error
    })
    : await loginByCode(account.value, code.value ).then((response)=>{
      return response
    }).catch((error)=>{
     return error
    })
console.log(res)
// console.log(res.response.status)
if(res.status!==201){
    if(res.response.status==402){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
    }
    if(res.response.status==404){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
    }
    else{
        Toast.fail('登录失败')
        isRegistering.value=false;
        return
    }
}
// console.log(res.data.token)
// console.log(res.data.data)
  store.setUser(res.data.data,res.data.token)
 localStorage.setItem('tokenStr',res.data.token)
  Toast.success('登录成功')
  isRegistering.value=false;
  //说明： 存在route.query.returnUrl回跳地址=》跳转returnUrl地址，否则默认跳转个人中心
//   router.replace((route.query.returnUrl ) || '/user')
  router.push('/home')
}, 1000);

}


onUnmounted(() => {
    clearInterval(timer)
  })

 const clickRight=()=>{
    router.push('/register')
}
</script>

<style scoped>
@import '@/styles/login.scss';
  

</style>

